<template>
	<view class="shangc-box">
		<view class="shangc-neir">
			<label>
				名称:
			</label>
			<input type="text" v-model="sourceIndex"  @blur="onBlur"   placeholder="请输入名称">
			<view class="" @click="fuzhis(sourceIndex)">
				复制
			</view>
		</view>

		<view class="shangc-neir" v-for="(item,index) in arrcont" :key="index">
			<label :for="item.id">
				{{item.name}}
			</label>
			<input type="text" :id="item.id" :type="item.type" :placeholder="'请输入'  + item.name" v-model="item.text"
				name="">
			<view class="" v-show="item.yuan" >
				元
			</view>
		</view>
		<view class="shangc-neir" @click="showType">
			<view>分类</view>
			<picker style="flex: 1;text-align: center;" mode="multiSelector" :range="pickerRange" :value="pickerValue"
				@change="unpType" @cancel="onCancel" @columnchange='onChange'>
				<view class="">
					{{selectedMain}}
				</view>
			</picker>
		</view>
		<view class="shangc-neir">
			<picker mode="selector" :range="options" :value="selectedIndex" @change="onSelectorChange">
				<view class="picker">
					<view class="">
						仓库
					</view>
					<view class="juzhong">
						{{ options[selectedIndex] }}
					</view>
				</view>
			</picker>
		</view>

		<view class="shangc-neir">
			<picker mode="selector" :range="kouan" @change="kouanadd">
				<view class="picker">
					<view class="">
						扣眼
					</view>
					<view class="juzhong">
						{{kouan[kouanIndex]}}
					</view>
				</view>
			</picker>
		</view>

		<view class="shangc-neir">
			<picker mode="selector" :range="mos" @change="mosadd">
				<view class="picker">
					<view class="">
						模式
					</view>
					<view class="juzhong">
						{{mos[mosIndex]}}
					</view>
				</view>
			</picker>
		</view>

		<view class="imgasea">
			<l-upload uploadType='img' @complete="complete" @remove="remove" ref="childRef"></l-upload>
		</view>
		<view class="unpdata" @click="unpdflin">
			新增商品
		</view>
	</view>
</template>

<script>
	import api from '../../api/Channel.js'
	import commonMixin from '@/mixins/qiLiuyun.js';
	import request from '../../api/index.js'
	import suffixAddress from '../../api/suffixAddress.js'
	export default {
		mixins: [commonMixin],
		data() {
			return {
				arrcont: [{
						name: '价格',
						text: null,
						type: 'digit',
						hou: '元',
						id: 1,
						yuan:true
					},
					{
						name: '大小',
						text: null,
						type: 'text',
						hou: '元',
						id: 2
					}
				],
				arrimgas: [],
				qiniuyunImage: [],
				showPicker: true, // 控制picker显示隐藏
				pickerValue: [0, 0], // 当前选中索引 [主分类索引, 子分类索引]
				categories: [],
				pickerRange: [
					[],
					[]
				], // picker需要的二维数组 [[主分类数组], [子分类数组]]
				selectedMain: '请选择分类',
				selectedSub: '',
				commodities: [],
				categoryId: null,
				options: ['柜台', '仓库 ', '虎门'],
				selectedIndex: 0,
				mos: ['1/20', '2/20', '3/20', '4/20', '5/20', '6/20', '7/20', '8/20', '9/20', '10/20', '11/20', '12/20',
					'13/20', '14/20', '15/20', '16/20', '17/20', '18/20', '19/20', '20/20'
				],
				mosIndex: 0,
				kouan: ['明眼', '暗眼'],
				kouanIndex: 0,
				sourceIndex:''
			};
		},
		onLoad() {
			this.acategories()
		},
		methods: {
			onBlur(){
				
			},
			unpType(e) {
				let th = this
				const mainIndex = e.detail.value[0];
				const subIndex = e.detail.value[1];
				const mainName = this.pickerRange[0][mainIndex];
				const subName = this.pickerRange[1][subIndex];
				this.selectedMain = mainName;
				this.selectedSub = subName;
				if (subName == undefined) {
					this.selectedMain = mainName
				}
				this.selectedMain = subName
				this.commodities.forEach((elenent, index) => {
					if (elenent.name == mainName) {
						elenent.children.forEach((elen, index) => {
							if (elen.name == subName) {
								th.categoryId = elen.id
							}
						})
						if (elenent.children.length == 0) {
							th.categoryId = elenent.id
							th.selectedMain = elenent.name
						}
					}
				})
				console.log(th.categoryId)
				// console.log('选中的主分类:', mainName);
				// console.log('选中的子分类:', subName);
			},
			showType(e) {
				this.showPicker = true
			},
			onChange(e) {
				const column = e.detail.column;
				const value = e.detail.value;

				// 如果是第一列变动（主分类）
				if (column === 0) {
					const mainIndex = value;

					// 更新二级分类数据
					const subCategories = this.commodities[mainIndex]?.children.map(child => child.name) || [];

					// 更新 pickerRange 第二列
					this.pickerRange[1] = subCategories;

					// 重设 pickerValue（保持第一列当前值，第二列归0）
					this.pickerValue = [mainIndex, 0];
				} else {
					// 如果是第二列变动，仅更新 pickerValue
					this.pickerValue[1] = value;
				}
			},
			onCancel(e) {
				this.showPicker = false;
				console.log('取消选择了分类');
			},
			async acategories() {
				let obj = {
					url: api.ctrl + suffixAddress.add().commodities,
				}
				let res = await request(obj)
				this.commodities = res.data // 假设你的数据在 res.data

				// 提取一级分类名
				const mainCategories = this.commodities.map(item => item.name)
				// 提取第一个一级分类的子分类名
				const subCategories = this.commodities[0]?.children.map(child => child.name) || []

				this.pickerRange = [mainCategories, subCategories]
			},
			remove(e) {
				// console.log(e)
				// this.qiniuyunImage.splice(e.index, 1);
				// console.log(this.qiniuyunImage)
			},
			async complete(e) {
				this.arrimgas = e.imageArr
			},
			async unpdflin() {
				let th = this;
				if (this.arrimgas.length == 0) {
					uni.showToast({
						title: '请上传图片',
						icon: 'error', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				} else if (th.arrcont[0].text == '') {
					// uni.showToast({
					// 	title: '请输入价格',
					// 	icon: 'error', // 可选值：success、loading、none
					// 	duration: 1000 // 显示时长（单位：ms）
					// });
					// return
				} else if (th.arrcont[1].text == '') {
					// uni.showToast({
					// 	title: '请输入大小',
					// 	icon: 'error', // 可选值：success、loading、none
					// 	duration: 1000 // 显示时长（单位：ms）
					// });
					// return
				} else if (th.categoryId == null) {
					uni.showToast({
						title: '请输入分类',
						icon: 'error', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				}
				if(th.sourceIndex == ''){
					uni.showToast({
						title: '请输入名称',
						icon: 'error', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				}


				if ( this.arrimgas.length %  (th.mosIndex*1 + 1)  != 0) {
					uni.showToast({
						title: '模式不符合',
						icon: 'none', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				}

				uni.showLoading({
					title: '上传中...'
				});
				// 同时发起所有上传请求，并在所有完成后同步处理结果
				// 如果发现 filePath 总是同一个，建议使用传统 for 循环，确保每次迭代都获取正确的路径
				this.qiniuyunImage = []
				for (const filePath of this.arrimgas) {
					// 等待上一张上传完成才继续下一张
					let key = await this.Tokenqiniu(filePath.url)
					console.log('上传文件路径：', filePath)
					console.log('返回的 key：', key)
					this.qiniuyunImage.push(key)
				}
				this.UploadProducts()
			},
			async UploadProducts() {
				let th = this
				let source = '';
				if (th.options[th.selectedIndex] == '柜台') {
					source = 1
				} else if (th.options[th.selectedIndex] == '仓库') {
					source = 2
				} else if (th.options[th.selectedIndex] == '虎门') {
					source = 3
				}
				
				let arr = [{ name: '', coverList: [] }];
				const inputArray = this.qiniuyunImage;
				const chunkSize = (th.mosIndex*1 + 1); // 分组大小（变量）
				
				// 遍历输入数组，按chunkSize分组处理
				for (let i = 0; i < inputArray.length; i += chunkSize) {
				  const chunk = inputArray.slice(i, i + chunkSize);
				  
				  // 检查arr中最后一个对象的coverList是否已满
				  const lastObj = arr[arr.length - 1];
				  if (lastObj.coverList.length < chunkSize) {
				    // 未满则填充当前分组
				    lastObj.coverList.push(...chunk);
				  } else {
				    // 已满则创建新对象并填充
				    arr.push({ name: '', coverList: chunk });
				  }
				}
				let obj = {
					data: {
						"sourceIndex":th.sourceIndex,
						"desc": "",
						"categoryId": th.categoryId,
						"salePrice": th.arrcont[0].text,
						"source": source,
						"size": th.arrcont[1].text,
						"eyeletType": th.kouan[th.kouanIndex],
						"items": arr
					},
					url: api.ctrl + '/commodities/batch',
					method: "POST",
				}
				let res = await request(obj)
				console.log(res)
				uni.hideLoading()
				uni.showToast({
					title: '上传成功',
					icon: 'success', // 可选值：success、loading、none
					duration: 1000 // 显示时长（单位：ms）
				});
				//商品图片变成空
				th.qiniuyunImage = []
				th.$refs.childRef.childMethod()
			},
			onSelectorChange(e) {
				this.selectedIndex = e.detail.value
			},
			mosadd(e) {
				this.mosIndex = e.detail.value
			},
			kouanadd(e) {
				this.kouanIndex = e.detail.value
			},
			fuzhis(sourceIndex){
				if(sourceIndex == ''){
					uni.showToast({
						title: '不能复制空的',
						icon: 'error'
					});
					return
				}
				uni.setClipboardData({
					data:sourceIndex,
					success() {
						uni.showToast({
							title: '复制成功',
							icon: 'success'
						});
					}
				})
			}
		}
	}
</script>

<style lang="less">
	.shangc-box {
		background-color: #F5F5F5;
		padding-top: 40upx;
	}

	.shangc-neir {
		background-color: #fff;
		padding: 40upx;
		box-sizing: border-box;
		display: flex;
		width: 100vw;
		border-bottom: 1px solid #F5F5F5;

		>input {
			flex: 1;
			text-align: center;
		}
	}

	.imgasea {
		padding-left: 25rpx;
	}

	.unpdata {
		box-sizing: border-box;
		padding: 20rpx;
		margin: 20rpx;
		text-align: center;
		background: #FF9900;
		border-radius: 20rpx;
		font-size: 40rpx;
		// color: #F5F5F5;
	}

	.picker {
		display: flex;
	}

	.juzhong {
		width: 500rpx;
		text-align: center;
	}
</style>